package cn.highedu.controller;

import cn.highedu.entity.UserDTO;
import cn.highedu.service.IUserService;
import cn.highedu.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/users")
@Slf4j
@Validated // 声明当前控制器类需要数据验证
public class UserController {
    // 注入UserService
    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/add-user")
    public String addUser(@RequestBody @Valid UserDTO userDTO) { // @Valid注解表示当前的对象需要数据验证
        log.debug("保存用户信息, 参数: {}", userDTO);
        return "success";
    }
    @PostMapping("/create-user")
    public String createUser(@RequestBody UserDTO userDTO) {
        log.debug("保存用户信息, 参数: {}", userDTO);
        userService.createUser(userDTO.getUsername(),
                userDTO.getPassword(),
                userDTO.getEmail(),
                userDTO.getPhone(),
                userDTO.getAddress());
        return "success";
    }
    @ExceptionHandler(ConstraintViolationException.class) // 声明要捕获的异常类型
    @ResponseStatus(HttpStatus.BAD_REQUEST) // 声明错误的请求类型
    public Map<String, String> handleValidationException(ConstraintViolationException e) {
        Map<String, String> errors = new HashMap<>();
        // 获取所有的异常信息
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        // 遍历异常信息集合 存储到Map集合中
        for (ConstraintViolation<?> violation : constraintViolations) {
            // 获取错误的名字
            String name = violation.getPropertyPath().toString();
            // 获取错误的内容
            String message = violation.getMessage();
            errors.put(name, message);
        }
        return errors;
    }

}
